import request from '../util/request'

// 获取当前数据库所有的表
export const getDataTableList = (data) => {
  return request({
    method: 'POST',
    url: '/base/getTableList',
    data: data
  })
}

// 根据表名称查询列
export const getDataTableColumnList = (tableName) => {
  return request({
    method: 'GET',
    url: '/base/getTableColumnList',
    params: { tableName: tableName }
  })
}

// 保存表
export const add = (data) => {
  return request({
    method: 'POST',
    url: '/genTable/add',
    data: data
  })
}

// 根据表的 ids 批量生成代码（对于已经保存到生成预设的表信息进行生成）
export const createByIds = (ids) => {
  return request({
    method: 'POST',
    url: '/genTable/createByIds',
    data: { ids: ids }
  })
}

// 根据表的 ids 批量生成代码（zip）
export const createZipByIds = (ids) => {
  return request({
    method: 'POST',
    url: '/genTable/createZipByIds',
    data: { ids: ids }
  })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} 文件类型 'application/zip' 或者 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
 */
export function resolveBlob (res, mimeType) {
  const aLink = document.createElement('a')

  var blob = new Blob([res.data], { type: mimeType })

  // //从 response 的 headers 中获取 filename, 后端 response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

// 根据id获取表详情
export const get = (data) => {
  return request({
    method: 'POST',
    url: '/genTable/get',
    data: data
  })
}

// 根据id获取表详情
export const pageList = (data) => {
  return request({
    method: 'POST',
    url: '/genTable/pageList',
    data: data
  })
}

// 根据id更新表数据
export const update = (data) => {
  return request({
    method: 'POST',
    url: '/genTable/update',
    data: data
  })
}

// 根据表名称删除表数据
export const delByGenTableName = (data) => {
  return request({
    method: 'POST',
    url: '/genTable/delByGenTableName',
    data: { name: data }
  })
}

// 获取生成方式
export const findGenTypeList = () => {
  return request({
    method: 'GET',
    url: '/genTable/getGenTypeList',
    params: null
  })
}

// 导入
export const importTableBatch = (names) => {
  return request({
    method: 'POST',
    url: '/genTable/import',
    data: { names: names }
  })
}

// 预览
export const preview = (data) => {
  return request({
    method: 'GET',
    url: '/genTable/preview',
    params: data
  })
}
